<template>
  <div>
    <el-form ref="form" label-width="80px" label-position="left">
      <el-form-item label="SPU名称">
        <el-input
          placeholder="SPU名称"
          type="text"
          style="width: 200px"
          v-model="spuFromInfo.spuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="trademark">
          <el-option
            v-for="item in trademarkList"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="SPU描述"
          style="width: 400px"
          :autosize="{ minRows: 4, maxRows: 10 }"
          v-model="spuFromInfo.description"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片">
        <el-upload
          action="/list-api/admin/product/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleAvatarSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="50%" :src="dialogImageUrl" /> </el-dialog
      ></el-form-item>

      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${filterSaleAttrList.length}个未选择`"
          v-model="saleAttr"
        >
          <el-option
            v-for="saleAttr in filterSaleAttrList"
            :key="saleAttr.id"
            :label="saleAttr.name"
            :value="saleAttr.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addSaleAttr(saleAttr)"
          >添加销售属性</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-table :data="spuSaleAttrList" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="180" align="center">
          </el-table-column>
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            width="360"
            align="center"
          >
          </el-table-column>
          <el-table-column label="属性名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                type="success"
                style="margin-right: 10px"
                v-for="item in row.spuSaleAttrValueList"
                :key="item.id"
                >{{ item.saleAttrValueName }}</el-tag
              >
              <el-input
                class="input-new-tag"
                v-if="row.inputShow"
                :ref="'input_' + $index"
                v-model="inputValue"
                @blur="inputBlur(row, $index)"
              ></el-input>
              <el-button
                v-else
                size="mini"
                style="margin-left: 10px"
                @click="addSaleAttrValueName(row, $index)"
                >添加</el-button
              >
            </template>
          </el-table-column>
        </el-table></el-form-item
      >
      <el-form-item style="margin-top: 20px">
        <el-button type="primary" @click="saveSpuFrom()">保存</el-button>
        <el-button @click="cancelSpuFrom()">取消</el-button></el-form-item
      >
    </el-form>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
export default {
  name: "spuFrom",
  data() {
    return {
      //表单收集的数据
      spuFromInfo: {
        spuName: "",
        tmId: "",
        id: "",
        description: "",
        spuSaleAttrList: [],
      },
      spuSaleAttrList: [],
      dialogImageUrl: "",
      dialogVisible: false, // 显示图片
      trademarkList: [], // 品牌信息
      trademark: "", // 选中的值
      saleAttrList: [], // 销售属性
      // filterSaleAttrList: [], // 过滤后可以选择的销售属性
      saleAttr: "", // 选中的平台属性
      spuImageList: [], // 图片列表
      inputValue: "", // 输入框的值
      category3Id: 0,
    };
  },
  mounted() {},
  methods: {
    // 新增spuFrom的回调
    async getAddSpuInfo(category3Id) {
      let trademarkList = await this.$api.spu.getTrademarkList();
      this.trademarkList = trademarkList.data;
      let baseSaleAttrList = await this.$api.spu.getBaseSaleAttrList();
      this.saleAttrList = baseSaleAttrList.data;
      this.category3Id = category3Id;
    },
    // 编辑spuFrom的回调
    async getSpuInfo(spuFromInfo) {
      if (spuFromInfo.id === undefined) {
        //没有id是为新增spu
        this.getAddSpuInfo(spuFromInfo);
        return;
      }
      this.spuFromInfo = spuFromInfo;
      try {
        const [spuRes, imgInfoListRes, trademarkListRes, saleAttrListRes] =
          await Promise.all([
            this.$api.spu.getSpuById(spuFromInfo.id),
            this.$api.spu.getSpuImageList(spuFromInfo.id),
            this.$api.spu.getTrademarkList(),
            this.$api.spu.getBaseSaleAttrList(),
          ]);
        // 从各个请求结果中获取数据
        const spuData = spuRes.data;
        spuData.spuSaleAttrList.forEach((item) => {
          item.inputShow = false;
        });
        this.spuFromInfo = spuData;
        this.spuSaleAttrList = spuData.spuSaleAttrList;
        this.trademark = spuData.tmId;
        this.imgInfoList = imgInfoListRes;
        this.trademarkList = trademarkListRes.data;
        this.saleAttrList = saleAttrListRes.data;
        // 处理数据
      } catch (error) {
        console.log(error);
      }
    },
    //图片删除
    handleRemove(file, fileList) {
      let res;
      fileList.forEach((item) => {
        res.push(item.response.data);
      });
      this.spuImageList = res;
    },
    //查看图片 放大镜功能
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //文件上传成功
    handleAvatarSuccess(res, file) {
      let id = nanoid();
      let obj = {
        imgName: id,
        imgUrl: res.data,
      };
      this.spuImageList.push(obj);
    },
    //添加销售属性
    addSaleAttr(saleAttr) {
      let obj;
      if (saleAttr !== -1) {
        this.saleAttrList.forEach((item) => {
          if (item.id === saleAttr) {
            obj = {
              baseSaleAttrId: item.id,
              saleAttrName: item.name,
              inputShow: false,
              spuSaleAttrValueList: [],
            };
          }
        });
        this.spuSaleAttrList.push(obj);
      }
    },
    //添加销售属性值名称
    addSaleAttrValueName(row, index) {
      console.log(index);
      //显示输入框
      row.inputShow = !row.inputShow;
      // 获得焦点
      this.$nextTick(() => {
        this.$refs["input_" + index]?.focus();
      });
    },
    inputBlur(row, index) {
      //失去焦点 保存和添加数据,清空输入框数据,隐藏输入框
      if (this.inputValue.length > 0) {
        let obj = {
          baseSaleAttrId: row.baseSaleAttrId,
          saleAttrName: row.saleAttrName,
          saleAttrValueName: this.inputValue,
        };
        row.spuSaleAttrValueList.push(obj);
        this.inputValue = "";
        row.inputShow = !row.inputShow;
      } else {
        row.inputShow = !row.inputShow;
      }
    },
    cancelSpuFrom() {
      //返回后通知父组件重新获取数据 ,隐藏子组件
      this.$emit("changeScene", 0);
    },
    //保持skuFrom数据
    async saveSpuFrom() {
      //整理数据 有id为编辑，无id为新增
      if (this.spuFromInfo.id === "") {
        console.log(this.spuFromInfo);
        this.spuFromInfo.category3Id = this.category3Id;
        this.spuFromInfo.spuSaleAttrList = this.spuSaleAttrList;
        this.spuFromInfo.spuImageList = this.spuImageList;
        let res=await this.$api.spu.saveSpuInfo(this.spuFromInfo);
        if (res.code === 200) {
          this.$message({ type: "success", message: "保存成功" });
          this.$emit("changeScene", 0);
        }
        return;
      }
      // 去除 "inputShow"
      this.spuSaleAttrList.forEach((item) => {
        delete item.inputShow;
      });
      this.spuFromInfo.spuImageList = this.spuImageList;
      console.log(this.spuFromInfo);
      let res = await this.$api.spu.updateSpuInfo(this.spuFromInfo);
      if (res.code === 200) {
        this.$message({ type: "success", message: "保存成功" });
        this.$emit("changeScene", 0);
      }
    },
  },
  computed: {
    filterSaleAttrList() {
      return this.saleAttrList.filter((saleAttr) => {
        if (this.spuFromInfo.id === "") {
          return true;
        } else {
          return this.spuFromInfo?.spuSaleAttrList?.every((item) => {
            return item.baseSaleAttrId !== saleAttr.id;
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>